﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPUMoniterWPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        System.Timers.Timer refreshTimer = new System.Timers.Timer(1000);
        private System.Windows.Forms.NotifyIcon _notifyIcon = null;

        const int CHILD_CPU_BLOCK_SIZE = 16;
        public MainWindow()
        {
            InitializeComponent();
            InitialTray();
        }

        PerformanceCounter CounterTotalCpu;
        PerformanceCounter[] CounterChildCPU;

        #region 最小化系统托盘
        private void InitialTray()
        {
            //设置托盘的各个属性
            _notifyIcon = new System.Windows.Forms.NotifyIcon();
            _notifyIcon.Text = "CPU使用率监视器";
            _notifyIcon.Visible = true;//托盘按钮是否可见
            _notifyIcon.Icon = Properties.Resources.app;

            _notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(
                new System.Windows.Forms.MenuItem[] {
                    new System.Windows.Forms.MenuItem("显示",(s, e)=>{ this.Show();}),
                    new System.Windows.Forms.MenuItem("关于",(s, e)=>{ menuFormAbout_Click(s,null); }),
                    new System.Windows.Forms.MenuItem("退出",(s, e)=>{ menuFormExit_Click(s,null); }),
                });

            _notifyIcon.MouseDoubleClick += (s, e) => { this.Show(); };
        }

        #endregion

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ReleaseCapture();
            SendMessage(new WindowInteropHelper(System.Windows.Application.Current.MainWindow).Handle, 0x0112, 0xF012, 0);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Init();
        }

        private void Init()
        {
            this.Left = SystemParameters.PrimaryScreenWidth - 300;
            this.Top = 300;

            CounterTotalCpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            CounterChildCPU = new PerformanceCounter[Environment.ProcessorCount];
            for (int i = 0; i < CounterChildCPU.Length; i++)
            {
                CounterChildCPU[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
            }

            //处理子CPU格子
            int columnCount = Convert.ToInt32(Math.Ceiling((double)CounterChildCPU.Length / 2));
            gridChild.Width = columnCount * CHILD_CPU_BLOCK_SIZE;
            this.Width = gridTotal.Width + gridChild.Width;
            for (int i = 0; i < columnCount; i++)
            {
                gridChild.ColumnDefinitions.Add(new ColumnDefinition());
            }
            for (int i = 0; i < CounterChildCPU.Length; i++)
            {
                int idxX = i / 2;
                int idxY = (i % 2 == 0) ? 0 : 1;
                Grid tempGrid = new Grid();
                tempGrid.Name = "childGrid" + i;
                tempGrid.SetValue(Grid.ColumnProperty, idxX);
                tempGrid.SetValue(Grid.RowProperty, idxY);
                tempGrid.ToolTip = $"内核_{i + 1} 使用率";
                gridChild.Children.Add(tempGrid);
            }
            //定时器
            refreshTimer.AutoReset = true;
            refreshTimer.Elapsed += RefreshTimer_Elapsed;
            refreshTimer.Start();
        }

        private void RefreshTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lbTotal.Dispatcher.BeginInvoke(new Action(() =>
            {
                float value = CounterTotalCpu.NextValue();
                lbTotal.Content = Convert.ToInt32(value).ToString();
                gridTotal.Background = new SolidColorBrush(Helper.FormUtil.GetColor(value));

                for (int i = 0; i < CounterChildCPU.Length; i++)
                {
                    Grid currentGrid = null;
                    for (int j = 0; j < gridChild.Children.Count; j++)
                    {
                        if (((Grid)gridChild.Children[j]).Name == "childGrid" + i)
                        {
                            currentGrid = (Grid)gridChild.Children[j];
                            break;
                        }
                    }
                    if (currentGrid != null)
                        currentGrid.Background = new SolidColorBrush(Helper.FormUtil.GetColor(CounterChildCPU[i].NextValue()));
                }
            }));
        }

        private void menuFormAbout_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("https://gitee.com/somereason/cpu_moniter_wpf \n2018-6-29\n版本: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), "关于", MessageBoxButton.OK, MessageBoxImage.Asterisk);
        }

        private void menuFormExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _notifyIcon.Dispose();
        }

        private void menuFormHide_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();
        }
    }
}
